////////////////////////////////////////////////////////////////////////////////////////
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING THIS SOFTWARE
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2013, AerVision Technologies Pty Ltd, all rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of AerVision Technologies, may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors to demonstrate 
// www.AerCloud.net Framework as a Service API (FaaS), "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the copyright holder or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
////////////////////////////////////////////////////////////////////////////////////////

package com.aercloud.client.gui;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import org.apache.log4j.Logger;

import com.aercloud.client.util.AerCloudClient;

public class PanelStep1Controls extends JPanel {
    
    private static Logger log = Logger.getLogger(PanelStep1Controls.class);

    private static class LinkMouseListener extends MouseAdapter {
    
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            try {
                (new LinkRunner(new URI(PanelStep1Controls.URI_STRING))).execute();
            } catch (URISyntaxException use) {
                throw new AssertionError(use + ": " + PanelStep1Controls.URI_STRING);
            }
        }
    }

    private static class LinkRunner extends SwingWorker<Void, Void> {
    
        private final URI uri;
    
        private LinkRunner(URI u) {
            if (u == null) {
                throw new NullPointerException();
            }
            uri = u;
        }
    
        @Override
        protected Void doInBackground() throws Exception {
            Desktop desktop = Desktop.getDesktop();
            desktop.browse(uri);
            return null;
        }
    
        @Override
        protected void done() {
            try {
                get();
            } catch (ExecutionException ee) {
                LinkRunner.handleException(uri, ee);
            } catch (InterruptedException ie) {
                LinkRunner.handleException(uri, ie);
            }
        }
    
        private static void handleException(URI u, Exception e) {
            JOptionPane.showMessageDialog(null, "Problem occurred while trying to open this link in your system's standard browser.", "A problem occured", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    public static final String URI_STRING = "https://www.aercloud.net";
    
    private File propertiesDir;
    private File propertiesFile;
    private Properties properties;
    
    private JTextField textField;
    private JButton btnConnect;
    private JLabel accessKeyLabel;
    private JLabel lblTextField;

    /**
     * Create the panel.
     */
    public PanelStep1Controls() {
        FlowLayout flowLayout = (FlowLayout) getLayout();
        flowLayout.setAlignment(FlowLayout.LEFT);
        add(getLblTextField());
        add(getTextField());
        add(getBtnConnect());
        add(getAccessKeyLabel());
    }
    
    private File getPropertiesDir() {
        if(propertiesDir == null) {
            propertiesDir = new File("./resources/settings");
            propertiesDir.mkdirs();
        }
        return propertiesDir;
    }
    
    private File getPropertiesFile() {
        if(propertiesFile == null) {
            propertiesFile = new File(getPropertiesDir(),"aercloudclient.properties");
        }
        return propertiesFile;
    }

    private Properties getProperties() {
        if(properties == null) {
            properties = new Properties();
            try {
                properties.load(new FileInputStream(getPropertiesFile()));
            } catch (Exception e) {
                log.debug("Failed to load application properties", e);
            }
        }
        return properties;
    }

    public String getAccessKey() {
        return getProperties().getProperty("AccessKey", "");
    }
    
    public synchronized boolean connect(AerCloudClient aerCloudClient) {
        if(aerCloudClient.initConnection(getTextField().getText())) {
            getProperties().setProperty("AccessKey", getTextField().getText());
            try {
                getProperties().store(new FileOutputStream(getPropertiesFile()),"");
            } catch (Exception e) {
                log.debug("Failed to store application properties", e);
            }
            return true;
        }
        return false;
    }

    public JTextField getTextField() {
        if (textField == null) {
        	textField = new JTextField();
        	textField.setColumns(10);
        	textField.setText(getProperties().getProperty("AccessKey", null));
        }
        return textField;
    }
    
    public JButton getBtnConnect() {
        if (btnConnect == null) {
        	btnConnect = new JButton();
        }
        return btnConnect;
    }
    
    public JLabel getAccessKeyLabel() {
        if (accessKeyLabel == null) {
        	accessKeyLabel = new JLabel("<html> You can obtain access key from&nbsp;&nbsp;<a href=\"\">AerCloud.net</a></html>");
        	accessKeyLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
        	accessKeyLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
            if (isBrowsingSupported()) {
                accessKeyLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
                accessKeyLabel.addMouseListener(new LinkMouseListener());
            }
        }
        return accessKeyLabel;
    }

    private static boolean isBrowsingSupported() {
        if (!Desktop.isDesktopSupported()) {
            return false;
        }
        boolean result = false;
        Desktop desktop = java.awt.Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            result = true;
        }
        return result;
    
    }
    
    public JLabel getLblTextField() {
        if (lblTextField == null) {
        	lblTextField = new JLabel("Enter Access Key: ");
        }
        return lblTextField;
    }
}
